local IndexController = Class('controllers.index', LoadApplication('controllers.base'))
local func = LoadLibrary('function')
local mysql = LoadLibrary('mysql')
local redis = LoadLibrary('redis')
local cache = redis:new();
local user = LoadModel('userModel')

function IndexController:__construct()
    self.parent:__construct()
    cache:select(4);
end

function IndexController:index()
    local p = {}
    --local db = string.format("%03d", math.fmod(os.date("%d"), 10));
    local dbn = func.rand(1, 10);
    local db = string.format("%03d", dbn);
    p['db'] = dbn;
    --城市列表
    local rows = cache:get('city');
    if not rows then
        local fields = "id,name,pyname,up";
        local sql = string.format([[select %s from co_sys_city where up=%s]], fields, 0)
        local res, err, errno, sqlstate = mysql:query(sql)
        if res then
            for i, v in ipairs(res) do
                sql = string.format([[select %s from co_sys_city where up=%s]], fields, v['id'])
                res[i]['sub'], err, errno, sqlstate = mysql:query(sql)
            end
            cache:setex('city', Registry['APP_CONF'].cacheexpire, json(res));
            rows = res;
        end
    else
        rows = func.json_decode(rows);
    end
    p['city'] = rows;
    --产品目录
    local rows = cache:get('catalog');
    if not rows then
        local fields = "id,name,up";
        local sql = string.format([[select %s from co_catalog where up=%s]], fields, 0)
        local res, err, errno, sqlstate = mysql:query(sql)
        if res then
            for i, v in ipairs(res) do
                sql = string.format([[select %s from co_catalog where up=%s limit 40]], fields, v['id'])
                res[i]['sub'], err, errno, sqlstate = mysql:query(sql)
            end
            cache:setex('catalog', Registry['APP_CONF'].cacheexpire, json(res));
            rows = res;
        end
    else
        rows = func.json_decode(rows);
    end
    p['catalog'] = rows;
    --主页产品目录
    local rows = cache:get('homecat');
    if not rows then
        local fields = "id,name,up";
        local sql = string.format([[select %s from co_catalog where up=%s]], fields, 0)
        local res, err, errno, sqlstate = mysql:query(sql)
        if res then
            for i, v in ipairs(res) do
                local limit = func.rand(10, 20);
                sql = string.format([[select %s from co_catalog where up=%s limit %s]], fields, v['id'], limit)
                res[i]['sub'], err, errno, sqlstate = mysql:query(sql)
            end
            cache:setex('homecat', Registry['APP_CONF'].cacheexpire, json(res));
            rows = res;
        end
    else
        rows = func.json_decode(rows);
    end
    p['homecat'] = rows;
    --图片
    local rows = func.json_decode(cache:get('images'));
    if not rows then
        local fields = "id,title,image,links";
        local sql = string.format([[select %s from co_images where type=%s]], fields, 1)
        local res, err, errno, sqlstate = mysql:query(sql)
        if res then
            cache:setex('images', Registry['APP_CONF'].cacheexpire, json(res));
            rows = res;
        end
    end
    p['images'] = rows;
    --产品
    local rows = func.json_decode(cache:get('goods'..db));
    if not rows then
        local fields = "id,name,thumb";
        local sql = string.format([[select %s from co_corp%s_goods order by rand() limit 50]], fields, db)
        local res, err, errno, sqlstate = mysql:query(sql)
        if res then
            cache:setex('goods'..db, Registry['APP_CONF'].cacheexpire, json(res));
            rows = res;
        end
    end
    p['goods'] = rows;
    --推荐公司
    local rows = func.json_decode(cache:get('corp'..db));
    if not rows then
        local fields = "id,name";
        local sql = string.format([[select %s from co_corp%s order by rand() limit 5]], fields, db)
        local res, err, errno, sqlstate = mysql:query(sql)
        if res then
            cache:setex('corp'..db, Registry['APP_CONF'].cacheexpire, json(res));
            rows = res;
        end
    end
    p['corp'] = rows;
    --最新注册公司
    local rows = func.json_decode(cache:get('newCorp'..db));
    if not rows then
        local fields = "id,name";
        local sql = string.format([[select %s from co_corp%s order by rand() desc limit 20]], fields, db)
        local res, err, errno, sqlstate = mysql:query(sql)
        if res then
            cache:setex('newCorp'..db, Registry['APP_CONF'].cacheexpire, json(res));
            rows = res;
        end
    end
    p['newCorp'] = rows;
    --最新注册产品
    local rows = func.json_decode(cache:get('newGoods'..db));
    if not rows then
        local fields = "id,name";
        local sql = string.format([[select %s from co_corp%s_goods order by rand() desc limit 20]], fields, db)
        local res, err, errno, sqlstate = mysql:query(sql)
        if res then
            cache:setex('newGoods'..db, Registry['APP_CONF'].cacheexpire, json(res));
            rows = res;
        end
    end
    p['newGoods'] = rows;

    local view = self:getView()
    view:assign(p)
    ngx.header.content_type = "text/html"
    return view:display();
end

function IndexController:category()
    local result = {};
    local p = {};
    local corp = {};
    local id = self.get.id;
    local db = string.format("%03d", self.get.db);
    p['db'] = self.get.db;
    if not id then
        local corpSql = "select id,up from co_catalog order by rand() limit 1";
        local corpRow, err, errno, sqlstate = mysql:query(corpSql);
        id = corpRow[1].id;
    end
    local page = tonumber(self.get.page);
    if not page then
        page = 1;
    end
    local size = 10;
    local offset = (page - 1) * size;
    repeat
        if not id then
            result = { ret = 1, msg = "ID为空" }
            break;
        end
        local fields = "id,name,up";
        local corpFields = "id,name,logo,main_products,address,register_capital,created_date,city_name";
        local sql = string.format([[select %s from co_catalog where id=%s limit 1]], fields, id)
        local res, err, errno, sqlstate = mysql:query(sql)
        if res[1].up == 0 then
            for i, v in ipairs(res) do
                local sql = string.format([[select %s from co_catalog where up=%s limit 100]], fields, v['id'])
                res[i]['sub'], err, errno, sqlstate = mysql:query(sql)
            end
            sql = string.format([[select %s from co_corp%s where category like '%s' limit %d offset %d]], corpFields, db, res[1]['sub'][1].name .. '%', size, offset);
            corp, err, errno, sqlstate = mysql:query(sql);
        else
            sql = string.format([[select %s from co_catalog where id=%s limit 1]], fields, res[1].up);
            res[1].upper, err, errno, sqlstate = mysql:query(sql);

            sql = string.format([[select %s from co_corp%s where category like '%s' limit %d offset %d]], corpFields, db, res[1].name .. '%', size, offset);
            corp, err, errno, sqlstate = mysql:query(sql);
        end
        p['category'] = res;
        p['corp'] = corp;
        local sql = string.format([[select count(*) as ttl from co_corp%s where category like '%s']], db, res[1].name .. '%');
        local total, err, errno, sqlstate = mysql:query(sql);
        local sql = string.format([[select %s from co_corp%s order by id DESC limit 15]], corpFields, db);
        p['newCorp'], err, errno, sqlstate = mysql:query(sql);
        local goodsFields = "name,id";
        local sql = string.format([[select %s from co_corp%s_goods order by id DESC limit 15]], goodsFields, db);
        p['hotGoods'], err, errno, sqlstate = mysql:query(sql);
        local sql = string.format([[select %s from co_corp%s_goods order by rand() limit 15]], goodsFields, db);
        p['recommendGoods'], err, errno, sqlstate = mysql:query(sql);
        p['pager'] = func.pager('/' .. db .. '/category/' .. id, page, math.ceil(total[1].ttl / size));
        local view = self:getView()
        ngx.header.content_type = "text/html"
        view:assign(p)
        return view:display();
    until (true)
    return json(result);
end

function IndexController:corp()
    local p = {};
    local result = {};
    local id = self.get.id;
    p['db']  = self.get.db;
    local db = string.format("%03d", self.get.db);
    repeat
        if not id then
            result = { ret = 1, msg = "ID为空" }
            break;
        end
        id = ndk.set_var.set_quote_sql_str(id);
        local view = self:getView()
        local fields = "*";
        local sql = string.format([[select %s from co_corp%s a inner join co_corp%s_info b on a.id=b.id where a.id=%s limit 1]], fields, db, db, id)
        local rows, err, errno, sqlstate = mysql:query(sql)
        if not rows[1] then
            result = { ret = 2, msg = "未找到此文档", data = { id = id, err = err } }
            break;
        end
        result = { ret = 0, msg = "文档内容", data = rows[1] }
        fields = "id,name,thumb,price,created_at";
        sql = string.format([[select %s from co_corp%s_goods where corp_id=%s limit 1]], fields, db, result['data'].id)
        result['data'].goods, err, errno, sqlstate = mysql:query(sql)
        local corpFields = "id,name";
        local sql = string.format([[select %s from co_corp%s t1 join (SELECT RAND() * (SELECT MAX(id) FROM co_corp%s) AS nid) t2 ON t1.id > t2.nid where category like '%s' limit 20]], corpFields, db, db, result['data'].category .. '%');
        result['data'].relateCorp, err, errno, sqlstate = mysql:query(sql);
        local sql = string.format([[select %s from co_corp%s t1 join (SELECT RAND() * (SELECT MAX(id) FROM co_corp%s) AS nid) t2 ON t1.id > t2.nid limit 20]], corpFields, db, db);
        result['data'].newCorp, err, errno, sqlstate = mysql:query(sql);
        view:assign(p)
        view:assign(result)
        return view:display();
    until (true)
    ngx.redirect('https://www.curr.cn/');
    return json(result);
end

function IndexController:goods()
    local p = {};
    local result = {};
    local id = self.get.id;
    p['db']  = self.get.db;
    local db = string.format("%03d", self.get.db);
    repeat
        if not id then
            result = { ret = 1, msg = "ID为空" }
            break;
        end
        id = ndk.set_var.set_quote_sql_str(id);
        local view = self:getView()
        local fields = "*";
        local sql = string.format([[select %s from co_corp%s_goods a inner join co_corp%s_goods_content b on a.id=b.id where a.id=%s limit 1]], fields, db, db, id)
        local rows, err, errno, sqlstate = mysql:query(sql)
        if not rows then
            result = { ret = 2, msg = "未找到此产品", data = { id = id, err = err } }
            break;
        end
        result = { ret = 0, msg = "产品内容", data = rows[1] }
        fields = "*";
        sql = string.format([[select %s from co_corp%s where id=%s limit 1]], fields, db, result['data'].corp_id)
        local corp, err, errno, sqlstate = mysql:query(sql)
        result['data'].corp = corp[1];
        local corpFields = "id,name,logo,main_products,address,register_capital,created_date,city_name";
        local sql = string.format([[select %s from co_corp%s t1 join (SELECT RAND() * (SELECT MAX(id) FROM co_corp%s) AS nid) t2 ON t1.id > t2.nid where category like '%s' limit 20]], corpFields, db, db, result['data'].corp.category .. '%');
        result['data'].relateCorp, err, errno, sqlstate = mysql:query(sql);
        local sql = string.format([[select %s from co_corp%s_goods t1 join (SELECT RAND() * (SELECT MAX(id) FROM co_corp%s_goods) AS nid) t2 ON t1.id > t2.nid limit 20]], fields, db, db, '%' .. result['data'].category .. '%');
        result['data'].relateGoods, err, errno, sqlstate = mysql:query(sql);
        result['data'].brief = func.cutstr(func.strip_tags(result['data'].content), 100);
        view:assign(p)
        view:assign(result)
        return view:display();
    until (true)
    return json(result);
end

function IndexController:corpgoods()
    local p = {};
    local result = {};
    local id = self.get.id;
    p['db']  = self.get.db;
    local db = string.format("%03d", self.get.db);
    repeat
        local page = tonumber(self.get.page);
        if not page then
            page = 1;
        end
        local size = 10;
        local offset = (page - 1) * size;
        local rows={};
        local goodscategory='';
        local category='';
        local fields = "*";
        local total = 0;
        if not id then
            id = '';
            local sql = string.format([[select %s from co_corp%s_goods limit %d offset %d]], fields, db, size, offset);
            rows, err, errno, sqlstate = mysql:query(sql)
            if not rows then
                result = { ret = 2, msg = "无产品"}
                break;
            end
            local sql = string.format([[select count(*) as ttl from co_corp%s_goods]], db);
            local totalRow, err, errno, sqlstate = mysql:query(sql);
            total = totalRow[1].ttl;
            result.corp = {name='公司产品', category='所有类别'};
        else
            local fields = "*";
            local sql = string.format([[select %s from co_corp%s_goods where corp_id='%s' limit %d offset %d]], fields, db, id, size, offset);
            rows, err, errno, sqlstate = mysql:query(sql)
            local sql = string.format([[select %s from co_corp%s where id='%s' limit 1]], fields, db, id);
            local corprows, err, errno, sqlstate = mysql:query(sql)
            result.corp = corprows[1];
            if func.empty(rows) then
                rows = {};
                total = 0;
            else
                local corp_id = rows[1].corp_id;
                category = corprows[1].category;
                local sql = string.format([[select count(*) as ttl from co_corp%s_goods where corp_id='%s']], db, id);
                local totalRow, err, errno, sqlstate = mysql:query(sql);
                total = totalRow[1].ttl;
                goodscategory=rows[1].category;
            end
        end
        result.list = rows;
        local corpFields = "id,name,logo,main_products,address,register_capital,created_date,city_name";
        local sql = string.format([[select %s from co_corp%s t1 join (SELECT RAND() * (SELECT MAX(id) FROM co_corp%s) AS nid) t2 ON t1.id > t2.nid where category like '%s' limit 20]], corpFields, db, db, category .. '%');
        result.relateCorp, err, errno, sqlstate = mysql:query(sql);
        local sql = string.format([[select %s from co_corp%s_goods t1 join (SELECT RAND() * (SELECT MAX(id) FROM co_corp%s_goods) AS nid) t2 ON t1.id > t2.nid where category like '%s' limit 20]], fields, db, db, '%' .. goodscategory .. '%');
        result.relateGoods, err, errno, sqlstate = mysql:query(sql);
        result['pager'] = func.pager('/' .. db .. '/corpgoods/' .. id, page, math.ceil(total / size));
        local view = self:getView()
        ngx.header.content_type = "text/html"
        view:assign(p)
        view:assign(result)
        return view:display();
    until (true)
    return json(result);
end

function IndexController:template()
    local result = {};
    local id = ndk.set_var.set_quote_sql_str(self.get.id);
    repeat
        if not id then
            result = { ret = 1, msg = "ID为空" }
            break;
        end
        local view = self:getView()
        local fields = "a.*,b.title as catName";
        local sql = string.format([[select %s from cu_template a inner join cu_template_cat b on a.cat_id=b.id where a.id=%s limit 1]], fields, id)
        local rows, err, errno, sqlstate = mysql:query(sql)
        if not rows then
            result = { ret = 2, msg = "未找到此文档", data = { id = id, err = err } }
            break;
        end
        if rows[1].label then
            rows[1].label = func.explode(',', rows[1].label);
        end
        result = { ret = 0, msg = "文档内容", data = rows[1] }
        view:assign(result)
        return view:display();
    until (true)
    return json(result);
    --do return view:render('index/index.html', p) end
end

function IndexController:userinfo()
    local result = {};
    repeat
        local token = self.get.token

        local rows = user.checktokenValid(token)
        if not rows then
            result = { ret = 0, msg = "token无效" }
            break;
        end
        result = { ret = 0, msg = "获取用户信息", data = rows }
    until (true)
    return json(result);
end

function IndexController:login()
    local result = {};
    repeat
        if func.empty(self.get.phone) or func.empty(self.get.password) then
            result = { ret = 100, msg = "phone或password 为空" }
            break;
        end
        local rows = user.get(self.get.phone)
        if not rows then
            result = { ret = 0, msg = "未找到此用户", data = { phone = self.get.phone, err = err } }
            break;
        end
        if rows.lockuntil > ngx.time() then
            result = { ret = 300, msg = "用户当前处于锁定状态", data = { lockuntil = os.date("%Y-%m-%d %H:%M:%S", rows.lockuntil) } }
            break;
        end
        if rows.userstatus == 0 then
            result = { ret = 400, msg = "用户已被冻结" }
            break;
        end
        result = user.checklogin(rows, self.get.password)
    until (true)
    return json(result)
end

function IndexController:register()
    local result = {};
    repeat
        if func.empty(self.get.phone) or func.empty(self.get.password) then
            result = { ret = 100, msg = "phone或password 为空" }
            break;
        end
        if self.get.password ~= self.get.repassword then
            result = { ret = 0, msg = "重复密码不一致" }
            break;
        end
        if user.checkphoneExists(self.get.phone) then
            result = { ret = 300, msg = "手机号码已存在" }
            break;
        end
        local rows = { phone = self.get.phone, password = self.get.repassword, regtime = ngx.time(), ip = func.getIp(), salt = func.randstr(16) }
        result = user.register(rows)
    until (true)
    return json(result)
end

function IndexController:resetpwd()
    local result = {};
    repeat
        local token = self.get.token

        local rows = user.checktokenValid(token)
        if not rows then
            result = { ret = 0, msg = "token无效" }
            break;
        end
        if func.empty(self.get.oldpassword) or func.empty(self.get.newpassword) then
            result = { ret = 300, msg = "新旧password 为空" }
            break;
        end
        if self.get.newpassword ~= self.get.repassword then
            result = { ret = 400, msg = "重复密码不一致" }
            break;
        end
        rows = user.get(rows.phone);
        local oldpassword = ngx.md5(self.get.oldpassword .. rows.salt);
        if rows.password ~= oldpassword then
            result = { ret = 500, msg = "旧密码不正确" }
            break;
        end
        local newpassword = ngx.md5(self.get.newpassword .. rows.salt);
        local rows = { phone = rows.phone, newpassword = newpassword }
        result = user.resetpwd(rows)
    until (true)
    return json(result)
end

function IndexController:updateinfo()
    local result = {};
    repeat
        local token = self.get.token

        local rows = user.checktokenValid(token)
        if not rows then
            result = { ret = 0, msg = "token无效" }
            break;
        end
        local data = { realname = self.get.realname, gender = self.get.gender, email = self.get.email, cityid = self.get.cityid, idcard = self.get.idcard }
        result = user.updateinfo(data, "uid=" .. rows['uid'])
        user.flushcache(self.get.token);
    until (true)
    return json(result);
end

function IndexController:uploadlogo()
    local result = {};
    repeat
        local token = self.get.token

        local rows = user.checktokenValid(token)
        if not rows then
            result = { ret = 0, msg = "token无效" }
            break;
        end
        local data = { avatar = self.get.avatar }
        result = user.uploadlogo(data, "uid=" .. rows['uid'])
        user.flushcache(self.get.token);
    until (true)
    return json(result);
end

function IndexController:checktoken()
    local result = {};
    repeat
        local token = self.get.token

        local rows = user.checktokenValid(token)
        if not rows then
            result = { ret = 0, msg = "token无效" }
            break;
        end
        result = { ret = 0, msg = "token有效" }
    until (true)
    return json(result);
end

function IndexController:sendnotice()
    local result = {};
    repeat
        local token = self.get.token
        local rows = user.checktokenValid(token)
        if not rows then
            result = { ret = 0, msg = "token无效" }
            break;
        end
        if func.empty(self.get.content) then
            result = { ret = 300, msg = "发送信息为空" }
            break;
        end
        local data = { uid = rows['uid'], content = self.get.content }
        if user.sendNotice(data) == true then
            result = { ret = 0, msg = "发送信息成功" }
        else
            result = { ret = 400, msg = "发送信息失败" }
        end
    until (true)
    return json(result);
end

function IndexController:getnotice()
    local result = {};
    repeat
        local token = self.get.token
        local rows = user.checktokenValid(token)
        if not rows then
            result = { ret = 0, msg = "token无效" }
            break;
        end
        local data = {};
        if func.empty(self.get.nid) then
            data = user.getNoticeAll(rows.uid)
        else
            data = user.getNotice(self.get.nid)
        end
        result = { ret = 0, msg = "获取信息成功", data = data }
    until (true)
    return json(result);
end

function IndexController:getcity()
    local result = {};
    repeat
        if not func.empty(self.get.up) then
            up = self.get.up
        else
            up = 0
        end

        local rows = func.json_decode(cache:get('city'));
        if not rows then
            local fields = "id,name,up";
            local sql = string.format([[select %s from cu_sys_city where up=%s]], fields, ndk.set_var.set_quote_sql_str(up))
            local res, err, errno, sqlstate = mysql:query(sql)
            if not res then
                result = { ret = 100, msg = "无数据被找到" }
                break;
            end
            cache:setex('city', Registry['APP_CONF'].cacheexpire, json(res));
            result = { ret = 0, msg = "城市列表", data = res }
            return json(result);
        end
        result = { ret = 0, msg = "城市列表", data = rows }
    until (true)
    return json(result);
end

return IndexController
